#include "GameStage.h"

GameStage::GameStage()
{
    initSDL();
    running = true;
}

GameStage::~GameStage()
{
    halt();
}

void GameStage::initSDL()
{
    SDL_Init(SDL_INIT_VIDEO);
    screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    imageLoader = new gcn::SDLImageLoader();
    gcn::Image::setImageLoader(imageLoader);
    graphics = new gcn::SDLGraphics();
    graphics->setTarget(screen);
    input = new gcn::SDLInput();

    font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    gcn::Widget::setGlobalFont(font);

    gui = new gcn::Gui();
    gui->setGraphics(graphics);
    gui->setInput(input);
    gui->setTop(this);
    setDimension(gcn::Rectangle(0, 0, 640, 480));
}

void GameStage::run()
{
    if(running)
    {
        while(SDL_PollEvent(&event))
        {
            if (event.type == SDL_KEYDOWN)
            {
                if (event.key.keysym.sym == SDLK_ESCAPE)
                {
                    running = false;
                }
            }
            else if(event.type == SDL_QUIT)
            {
                running = false;
            }

            input->pushInput(event);
        }

        gui->logic();
        gui->draw();

        SDL_Flip(screen);
    }
}

void GameStage::halt()
{
    delete font;
    delete gui;

    delete input;
    delete graphics;
    delete imageLoader;

    SDL_Quit();
}